using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
namespace Common.Sql
{
	public static class SQLServerHelper
	{
		public static List<string> EnumerateServers()
		{
			DataTable dataSources = SqlDataSourceEnumerator.Instance.GetDataSources();
			List<string> result;
			if (dataSources.Rows.Count < 1)
			{
				result = null;
			}
			else
			{
				List<string> list = new List<string>();
				foreach (DataRow dataRow in dataSources.Rows)
				{
					string text = dataRow["ServerName"].ToString();
					string text2 = dataRow["InstanceName"].ToString();
					list.Add(string.IsNullOrEmpty(text2) ? text : string.Format("{0}\\{1}", text, text2));
				}
				result = list;
			}
			return result;
		}
		public static List<string> EnumerateDatabases(string connectionString)
		{
			List<string> result;
			try
			{
				using (SqlConnection sqlConnection = new SqlConnection(connectionString))
				{
					sqlConnection.Open();
					DataTable schema = sqlConnection.GetSchema("Databases");
					sqlConnection.Close();
					if (schema.Rows.Count < 1)
					{
						result = null;
					}
					else
					{
						List<string> list = new List<string>();
						foreach (DataRow dataRow in schema.Rows)
						{
							list.Add(dataRow["database_name"].ToString());
						}
						result = list;
					}
				}
			}
			catch
			{
				result = null;
			}
			return result;
		}
		public static bool IsSqlServerInstalled()
		{
			bool result;
			using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Microsoft SQL Server\\", false))
			{
				if (registryKey == null)
				{
					result = false;
					return result;
				}
				string[] subKeyNames = registryKey.GetSubKeyNames();
				if (subKeyNames.Length == 0)
				{
					result = false;
					return result;
				}
				string[] array = subKeyNames;
				for (int i = 0; i < array.Length; i++)
				{
					string text = array[i];
					if (text.StartsWith("MSSQL."))
					{
						using (RegistryKey registryKey2 = registryKey.OpenSubKey(text, false))
						{
							if (registryKey2 != null)
							{
								string text2 = (string)registryKey2.GetValue("", "");
								if (text2.ToLower() == "perfect" || text2.ToLower() == "sqlexpress")
								{
									result = true;
									return result;
								}
							}
						}
					}
				}
			}
			result = false;
			return result;
		}
	}
}
